CODE 87. Permutations

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/20/2013-10-20-CODE 87 Permutations/

访问原文「CODE 87. Permutations

Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],
and [3,2,1].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public ArrayList<ArrayList<Integer>> permute(int[] num) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int n : num) {
numbers.add(n);
}
return dfs(numbers);
}
ArrayList<ArrayList<Integer>> dfs(ArrayList<Integer> numbers) {
if (numbers.size() <= 1) {
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> result = new ArrayList<Integer>(numbers);
results.add(result);
return results;
}
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> newNumbers = new ArrayList<Integer>(numbers);
for (int i = 0; i < numbers.size(); i++) {
Integer number = numbers.get(i);
newNumbers.remove(number);
ArrayList<ArrayList<Integer>> res = dfs(newNumbers);
for (ArrayList<Integer> re : res) {
re.add(0, number);
results.add(re);
}
newNumbers.add(number);
}
return results;
}
Jerky Lu wechat
欢迎加入微信公众号